package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
   @Autowired
   private DishFlavorService dishFlavorService;

   @Autowired
   private CategoryService categoryService;

    @Override
    public void addDish(DishDto dishDto) {
        //保存菜品信息，将dishDto里面的Dish数据自动映射过去
        //保存时，会通过雪花算法生成dish的id值
        this.save(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();
        //将dish的id保存到DishFlavor中
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }

        //批量保存口味
        dishFlavorService.saveBatch(flavors);
    }


    //获取菜品的基本信息和口味信息
    public DishDto getDishById(Long id){
        DishDto dishDto = new DishDto();
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish,dishDto);

        //添加获取到对应的口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        dishDto.setFlavors(dishFlavorService.list(queryWrapper));

        return dishDto;
    }

    @Override
    public void editDish(DishDto dishDto) {
        this.updateById(dishDto);
        //根据dishId修改口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //先删除原本的口味，再添加口味
        dishFlavorService.remove(queryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        //设置口味对应的菜品id
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
       dishFlavorService.saveBatch(flavors);
    }
}
